package AttachmentGroupService

import (
	"database/sql"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/service/BaseService"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"strings"
	"time"
)

func List(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	condition := g.Map{}
	obj := toolsDb.GetUnSafaTable(ctx, req.TableName)
	// 默认全部表别名先设置为 a
	asName := "a"
	// 处理查询的列
	selectFields := ""
	defaultSelectFields := strings.Split(obj.GetFieldsStr(), ",")

	listQueryOp := req.ListQueryOp
	if listQueryOp != nil {
		if listQueryOp.AsName != "" {
			asName = listQueryOp.AsName
		}
	}
	// 有设置表别名
	obj.As(asName)
	// 获取查询条件
	BaseService.GetCondition(r, condition, listQueryOp, asName)
	obj.Where(
		condition,
	)

	if listQueryOp != nil {
		if len(listQueryOp.SelectFields) > 0 {
			// 设置了 select 的
			selectFields = strings.Join(listQueryOp.SelectFields, ",")
		}
		if listQueryOp.OrderBy != "" {
			obj.Order(listQueryOp.OrderBy)
		}
	}
	// 设置 select
	if selectFields != "" {
		obj.Fields(selectFields)
	} else {
		for k, v := range defaultSelectFields {
			defaultSelectFields[k] = asName + "." + v
		}
		obj.Fields(strings.Join(defaultSelectFields, ","))
	}
	// 处理查询里 --- end ---
	// 设置 删除时间
	obj.Where(asName + ".delete_at < 1")

	if listQueryOp != nil {
		if listQueryOp.IsCache > 0 {
			obj.Cache(time.Duration(listQueryOp.IsCache)*time.Second,
				"backCache:"+req.TableName+":list:"+gmd5.MustEncrypt(condition))
		}
		for _, item := range listQueryOp.LeftJoin {
			obj.LeftJoin(item.TableInfo, item.Condition)
		}
	}

	res, err := obj.All()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	return response.SuccessByRequestMessageData(nil, "获取成功",
		res.List())
}
